<template>

  <div v-if="fileId">
    <div>{{ fileId }}</div>
    <el-button @click="updateData" type="primary">更新数据</el-button>
    <div>发送给服务端更新信号时间: {{ sndUpdateSignalTime }}</div>
    <div>收到服务端更新信号时间: {{ rcvUpdateSignalTime }}</div>
    <div>心跳最新时间: {{ heartBeatSignalTime }}</div>
    <div>服务器返回最新内容: {{ serverContent }}</div>
  </div>

  <div v-else-if="sessionId">
    <div>sessionId:{{ sessionId }}</div>
    <img width="200px" height="200px" :src="qrCode" alt="QR Code"/>
  </div>


</template>

<script>

import QRCode from "qrcode";

export default {
  name: "HelloWorld",
  data() {
    return {
      wsuri: "ws://192.168.0.110:7777/websocket",
      // wsuri: "ws://192.168.0.110:7890/websocket",
      // wsuri: "ws://192.168.2.186:28080/im/pdf",
      // wsuri: "ws://192.168.2.186:6543/pdf",
      ws: null,
      sessionId: '',
      qrCode: null,
      fileId: '',
      rcvUpdateSignalTime: '',
      sndUpdateSignalTime: '',
      heartBeatSignalTime: '',
      serverContent: '',
      heartbeatInterval: null,
      heartbeatIntervalTime: 3000, // 心跳间隔时间，单位为毫秒
    }
  },
  created() {
    //页面打开时，初始化WebSocket连接
    this.initWebSocket()
  },
  beforeDestroy() {
    // 页面销毁时，关闭WebSocket连接
    this.stopHeartbeat()
    this.fileId = ''
    try {
      this.ws.close()
    } catch (e) {

    }
    this.ws = null;
    this.sessionId = ''
  },
  methods: {
    // pc端更新附件数据后，向服务器端发送更新信号
    updateData() {
      console.error('snd update signal')
      this.ws.send(JSON.stringify({
        type: 0
      }))
      //格式化为  yyyy-MM-dd HH:mm:ss
      this.sndUpdateSignalTime = new Date().toLocaleTimeString()
      this.resetHeartbeat();
    },

    async generateQRCode() {
      try {
        this.qrCode = await QRCode.toDataURL(this.sessionId);
      } catch (error) {
        console.error('生成二维码时出错:', error);
      }
    },
    // 周期性发送心跳包
    startHeartbeat() {
      this.heartbeatInterval = setInterval(() => {
        if (this.ws && this.ws.readyState === WebSocket.OPEN) {
          this.ws.send(JSON.stringify({
            type: 100
          }))
          this.heartBeatSignalTime = new Date().toLocaleTimeString()
          console.error('snd heartbeat signal')
        } else {
          this.stopHeartbeat();
        }
      }, this.heartbeatIntervalTime);
    },
    //在发送或接受数据后,重置下一次发送心跳包的时间
    resetHeartbeat() {
      clearInterval(this.heartbeatInterval);
      this.startHeartbeat();
    },
    // 停止发送心跳包
    stopHeartbeat() {
      clearInterval(this.heartbeatInterval);
    },

    initWebSocket() {
      let that = this;
      this.ws = new WebSocket(this.wsuri);

      this.ws.onopen = () => {
        this.startHeartbeat();
      };
      // 接收后端消息
      this.ws.onmessage = function (event) {
        console.error('RECV:' + event.data)
        that.serverContent = event.data;
        let parse = JSON.parse(event.data);
        that.resetHeartbeat();

        switch (parse.type) {
          case 0: {
            console.error('update')
            that.rcvUpdateSignalTime = new Date().toLocaleTimeString()
            //TODO. 请求数据,刷新附件数据
            break;
          }
          case 1: {   //fileId list. 接受数据,进行路径跳转
            console.error('REQ:' + event.data)
            that.fileId = parse.fileId;
            break;
          }
          case 3: {
            that.sessionId = parse.sessionId;
            that.generateQRCode();
            break;
          }
        }
      };
      // 关闭连接时调用
      this.ws.onclose = function (event) {
        alert('连接已关闭');
        that.stopHeartbeat()
        // 强制刷新页面(created 会调用)
        location.reload(true)
      };
    }

  }
}
</script>

<style scoped>

</style>